package com.xl.bigdata.ai.tc.test;

import com.hankcs.hanlp.classification.classifiers.IClassifier;
import com.hankcs.hanlp.classification.classifiers.NaiveBayesClassifier;
import com.hankcs.hanlp.classification.models.NaiveBayesModel;
import com.hankcs.hanlp.corpus.io.IOUtil;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;

public class QingXuTextClassification
{
    public static final String CORPUS_FOLDER = "E:\\lexin\\sourceCode\\BoyBD\\data\\test\\情绪";
    public static final String MODEL_PATH = "E://lexin/sourceCode/BoyBD/data/test/qingxutextclassification-model.ser";

    public static void main(String[] args)
            throws IOException
    {
        IClassifier classifier = new NaiveBayesClassifier(trainOrLoadModel());

        predict(classifier, "“用户越来越生气“");
    }

    private static void predict(IClassifier classifier, String text)
    {
        if (!"其他".equals(classifier.classify(text))) {
            System.out.printf("《%s》 属于分类 【%s】\n", new Object[] { text, classifier.classify(text) });
        }
    }

    private static NaiveBayesModel trainOrLoadModel()
            throws IOException
    {
        NaiveBayesModel model = (NaiveBayesModel)IOUtil.readObjectFrom("E://lexin/sourceCode/BoyBD/data/test/qingxutextclassification-model.ser");
        if (model != null) {
            return model;
        }

        File corpusFolder = new File("E:\\lexin\\sourceCode\\BoyBD\\data\\test\\情绪");
        if ((!corpusFolder.exists()) || (!corpusFolder.isDirectory())) {
            System.err.println("没有文本分类语料，请阅读IClassifier.train(java.lang.String)中定义的语料格式与语料下载：https://github.com/hankcs/HanLP/wiki/%E6%96%87%E6%9C%AC%E5%88%86%E7%B1%BB%E4%B8%8E%E6%83%85%E6%84%9F%E5%88%86%E6%9E%90");

            System.exit(1);
        }

        IClassifier classifier = new NaiveBayesClassifier();
        classifier.train("E:\\lexin\\sourceCode\\BoyBD\\data\\test\\情绪");
        model = (NaiveBayesModel)classifier.getModel();
        IOUtil.saveObjectTo(model, "E://lexin/sourceCode/BoyBD/data/test/qingxutextclassification-model.ser");
        return model;
    }
}